package cn.amaake.magicplugin.nacos.module;

import cn.amaake.magicplugin.nacos.config.NacosConfig;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.spring.core.env.NacosPropertySource;
import org.ssssssss.magicapi.core.annotation.MagicModule;
import org.ssssssss.script.annotation.Comment;

@MagicModule("nacosconfig")
public class NacosConfigModule {

    private ConfigService configService;

    private NacosConfig nacosConfig;

    public NacosConfigModule(ConfigService configService, NacosConfig nacosConfig){
        this.configService = configService;
        this.nacosConfig = nacosConfig;
    }

    @Comment("获取远程配置")
    public String getconfig(@Comment("key(配置key)")String key) throws NacosException {
        String config = configService.getConfig(nacosConfig.getDataId(), nacosConfig.getGroup(), nacosConfig.getTimeout());
        NacosPropertySource nacosPropertySource = new NacosPropertySource(nacosConfig.getDataId(), nacosConfig.getGroup(), nacosConfig.getDataId()+"|"+nacosConfig.getGroup() ,config, nacosConfig.getType().getType());
        String value = nacosPropertySource.getSource().get(key).toString();
        return value;
    }

    @Comment("获取远程配置")
    public String getconfig(@Comment("dataId(远程dataId)")String dataId, @Comment("key(配置key)")String key) throws NacosException {
        String config = configService.getConfig(dataId, nacosConfig.getGroup(), nacosConfig.getTimeout());
        NacosPropertySource nacosPropertySource = new NacosPropertySource(dataId, nacosConfig.getGroup(), dataId+"|"+nacosConfig.getGroup() ,config, nacosConfig.getType().getType());
        String value = nacosPropertySource.getSource().get(key).toString();
        return value;
    }

    @Comment("获取远程配置")
    public String getconfig(@Comment("dataId(远程dataId)")String dataId, @Comment("group(远程group)")String group,@Comment("key(配置key)")String key) throws NacosException {
        String config = configService.getConfig(dataId, group, nacosConfig.getTimeout());
        NacosPropertySource nacosPropertySource = new NacosPropertySource(dataId, group, dataId+"|"+group ,config, nacosConfig.getType().getType());
        String value = nacosPropertySource.getSource().get(key).toString();
        return value;
    }

}
